﻿using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Reflection;

namespace ObjectEditor
{
    /// <summary>
    /// Класс для редактирования свойства объекта типа коллекции.
    /// </summary>
    public class CollectionValue : BaseValue
    {
        protected IList Data { get; set; }
        public ObservableCollection<CollectionItem> Items { get; set; }

        public override object Value
        {
            get
            {
                return Property.GetValue(ObjectPointer, null);
            }
            set
            {
                Property.SetValue(ObjectPointer, value, null);
                UpdateValue(ObjectPointer);
            }
        }

        public CollectionValue(object objectPointer, PropertyInfo property) : base(objectPointer, property)
        {
            Items = new ObservableCollection<CollectionItem>();

            if (property.PropertyType.GetInterface("INotifyCollectionChanged") != null)
            {
                var notify = (INotifyCollectionChanged) property.GetValue(objectPointer, null);
                if (notify != null) notify.CollectionChanged += NotifyOnCollectionChanged;
            }

            UpdateValue(objectPointer);
        }

        private void NotifyOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            UpdateValue(ObjectPointer);
        }

        public override void UpdateValue(object objectPointer)
        {
            ObjectPointer = objectPointer;
            Data = Value as IList;

            if (Items != null) Items.Clear();

            if (Data == null)
            {
                InvokePropertyChanged("Value");
                return;
            }

            if (ObjectPointer != null && Data != null)
            {
                var index = 0;
                foreach (var item in Data)
                {
                    if (item != null) Items.Add(new CollectionItem(item, Data, index++));
                }
            }

            InvokePropertyChanged("Value");
        }
    }
}
